package com.hyq.learn.api.support;

import com.hyq.learn.api.config.datasource.DatasourceContextHolder;
import com.hyq.learn.api.enumtype.DatasourceType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.function.Supplier;

/**
 * 直接使用注解的方式执行对应数据库的查询方式
 * @author heyuqin
 * @date 2024/5/29 19:33
 */
@Deprecated
@Component
public class DatasourceSupport {
    private static final Logger LOGGER = LoggerFactory.getLogger(DatasourceSupport.class);

    public <T> T execute(DatasourceType datasourceType, Supplier<T> supplier) {
        DatasourceContextHolder.setDatasourceType(datasourceType);
        try {
            return supplier.get();
        } finally {
            DatasourceContextHolder.remove();
        }
    }

    /**
     * 主配置库执行
     */
    public <T> T execute(Supplier<T> supplier) {
        return execute(DatasourceType.MASTER, supplier);
    }

    public <T> T executeRetryable(Supplier<T> supplier) {
        return retry(() -> execute(supplier));
    }

    public <T> T executeRetryable(DatasourceType datasourceType, Supplier<T> supplier) {
        return retry(() -> execute(datasourceType, supplier));
    }

    private <T> T retry(Supplier<T> supplier) {
        int runTime = 0, retryTime = 3;
        while (++runTime <= retryTime) {
            try {
                return supplier.get();
            } catch (Exception e) {
                LOGGER.error("error when execute sql. run_time({}/{}), error:{}", runTime, retryTime, e.getMessage());
                if (runTime == retryTime) {
                    throw e;
                }
            }
        }
        return null;
    }

}
